﻿#include "FileCopyCtrl.h"

FileCopyCtrl::FileCopyCtrl(QObject *parent)
    : QObject(parent),
      m_mutex(QMutex::Recursive)
{
    m_worker.moveToThread(&m_exec_thread);
    m_exec_thread.start();
}

FileCopyCtrl::~FileCopyCtrl()
{
    stopAll();
}

void FileCopyCtrl::addCopyTask(QSharedPointer<FileCopyWorker::CopyTask> task)
{
    if (!task) return;

    QMutexLocker locker(&m_mutex);
    m_task_queue.push_back(task);

    // 尝试启动新任务
    tryStartNewTask();
}

void FileCopyCtrl::stopAll()
{
    // 停止执行等待退出
    m_worker.stopCurrent();
    m_exec_thread.quit();
    m_exec_thread.wait(2000);
}

void FileCopyCtrl::tryStartNewTask()
{
    QMutexLocker locker(&m_mutex);
    if (m_task_queue.isEmpty()) return;

    // 发送任务给工人执行
    QSharedPointer<FileCopyWorker::CopyTask> task = m_task_queue.takeFirst();
    QMetaObject::invokeMethod(&m_worker, "slotDoOneTask", Qt::QueuedConnection,
                              Q_ARG(QSharedPointer<FileCopyWorker::CopyTask>, task));
}
